import express from "express";
import multer from "multer";
import { findCommentsByLinkId } from "../model/comment.js";
import fs from 'fs';

import { addLike, getAllLinks, getAllTips, getLinkById, addVisitCnt, addLink, addTags, updateTags } from '../model/links.js'
import { findUserById } from "../model/user.js";

const linksRouter = express.Router()

//获取链接
linksRouter.post("/getLinks", async (req, res) => {
    const { tip } = req.body;

    const { userId } = req.cookies
    console.log(userId);

    const result = await getAllLinks();
    const allTips = await getAllTips();
    const { bookmark } = await findUserById(Number(userId))
    const bookmarkArr = JSON.parse(bookmark)

    const allLinks = result.map(link => {
        const isBookmarked = bookmarkArr.includes(link.id)

        return { ...link, isBookmarked }
    })

    const data = allLinks?.map((item) => {
        const tipsArr = JSON.parse(item.tips)
        const tips = tipsArr.map(item => {
            for (let i = 0; i < allTips.length; ++i) {
                if (allTips[i].id == item) return allTips[i];
            }
        })
        return {
            ...item,
            tips: tips
        }
    }).filter((item) => {
        if (tip) {
            for (let i = 0; i < item.tips.length; ++i) {
                if (item.tips[i]?.id == tip) {
                    return true
                }
            }
            return false

        }
        else return true
    })

    res.send({
        msg: 'ok',
        data
    })
})


const iconStorage = multer.diskStorage({
    //存储路径
    destination(req, file, cb) {
        cb(null, './icon/')
    },
    //文件名
    filename(req, file, cb) {
        cb(null, file.originalname)
    },
})
const iconupload = multer({ iconStorage })

linksRouter.post('/uploadIcon', iconupload.single('file'), (req, res) => {
    //文件会别自动上传到相应目录，并且upload.single('file')会将包含文件信息的对象挂载到req.file上

    const icon = '/icon/' + req.file.originalname
    fs.writeFileSync(`public/icon/${req.file.originalname}`, req.file.buffer)

    //更新url
    res.send({
        msg: 'ok',
        icon,
    })
})



//增加链接
/**
 * 这里有两种类型：
 * 1. 添加的链接的tag是已经有的tag,那么传一个tag id切记是number类型的数组 变量名为tips与数据库同名
 * 2. 有用户额外添加的新tags,统一保存到newTags的参数中，发送过来
 * 其他参数：
 * url
 * desc
 * name
 * icon
 */
linksRouter.post('/addLink', async (req, res) => {
    const { desc, name, url, tips, newTags, icon } = req.body;
    const userId = Number(req.cookies.userId)
    if (newTags) {

        const tags = newTags.map((item) => {
            return { tip: item }
        })
        await addTags(tags)

        const allTags = await getAllTips()

        allTags.filter(item => {
            if (newTags.includes(item.tip)) return true;
            return false
        }).forEach(item => {
            tips.push(item.id)
        })
    }

    const _tips = JSON.stringify(tips)
    const data = { desc, icon, name, url, tips: _tips, authorId: userId };
    if (!icon) {
        delete data.icon
    }
    const result = await addLink(data)
    res.send({
        msg: 'ok',
        data: result
    })
})

// 添加喜欢 搞定
linksRouter.get('/like', async (req, res) => {
    const { id } = req.query;
    const { likes } = await addLike(Number(id));

    res.send({
        msg: "ok",
        data: {
            likes,
            id
        }
    })
})

linksRouter.post('/updateTags', async (req, res) => {
    const { tips, id } = req.body;

    const result = await updateTags(tips, id)

    res.send({ msg: 'ok', data: result })
})

//拿到单独的链接 给链接 id
linksRouter.post('/getLink', async (req, res) => {
    const data = req.body;

    const { userId } = req.cookies

    const { bookmark } = await findUserById(Number(userId))
    const bookmarkArr = JSON.parse(bookmark)
    const isBookmarked = bookmarkArr.includes(Number(data.id))


    console.log(data);

    //每次访问单独的链接页 访问量++
    const link = await getLinkById({ id: Number(data.id) });
    await addVisitCnt(Number(data.id))

    const allTips = await getAllTips();
    const tipsArr = JSON.parse(link.tips)
    const tips = tipsArr.map(item => {
        for (let i = 0; i < allTips.length; ++i) {
            if (allTips[i].id == item) return allTips[i];
        }
        return allTips[0]
    })
    console.log(link);
    const uploadUserId = link.authorId;
    const author = await findUserById(uploadUserId)
    delete author.password;
    delete author.auth;

    //拿到对应的评论：
    const comments = await findCommentsByLinkId(Number(data.id))
    console.log(comments);
    //处理一下评论的用户：拿到头像和nikename
    const getUser = async (id, item) => {
        const user = await findUserById(Number(id))
        delete user.auth;
        delete user.password;
        return { user, comment: item }
    }

    const getComentsWithUser = async () => {
        let result = await Promise.all(comments.map(async (item) => {
            return await getUser(item.userId, item)
        }))
        return result;
    }

    const commentsWithUser = await getComentsWithUser()
    console.log(commentsWithUser);

    res.send({
        msg: 'ok',
        data: {
            ...link,
            tips,
            isBookmarked,
            author,
            comments: commentsWithUser
        }
    })
})
linksRouter.post('/comments', async (req, res) => {
    const data = req.body;
    console.log(data);
    const comments = await findCommentsByLinkId(Number(data.id))
    console.log(comments);
    //处理一下评论的用户：拿到头像和nikename
    const getUser = async (id, item) => {
        const user = await findUserById(Number(id))
        delete user.auth;
        delete user.password;
        return { user, comment: item }
    }

    const getComentsWithUser = async () => {
        let result = await Promise.all(comments.map(async (item) => {
            return await getUser(item.userId, item)
        }))
        return result;
    }

    const commentsWithUser = await getComentsWithUser()
    res.send({
        msg: 'ok',
        data: {
            comments: commentsWithUser
        }
    })


})

linksRouter.get('/tags', async (req, res) => {
    const tags = await getAllTips();
    res.send({
        msg: 'ok',
        data: tags
    })
})


export default linksRouter